package com.example.springbootdemo2.service.impl;

import com.example.springbootdemo2.mapper.db1.UserMapper;
import com.example.springbootdemo2.pojo.ExcelData;
import com.example.springbootdemo2.pojo.db1.User;
import com.example.springbootdemo2.service.ExcelService;
import com.example.springbootdemo2.utils.ExcelUtils;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.record.SaveRecalcRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Executable;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ExcelServiceImpl implements ExcelService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 方法名：
     * 功能：导出
     */
    @Override
    public Boolean exportExcel(HttpServletResponse response, String fileName, Integer pageNum, Integer pageSize) {
    
        log.info("开始导出数据！");
        List<User> userList = userMapper.selectUserList();
        List<String[]> list = new ArrayList<>();
        for (User user : userList) {
            String[] arrs = new String[userList.size()];
            arrs[0]=String.valueOf(user.getId());
            arrs[1]=String.valueOf(user.getUsername());
            arrs[2]=String.valueOf(user.getPassword());
            arrs[3]=String.valueOf(user.getPhone());
            arrs[4]=String.valueOf(user.getCreateTime());
            arrs[5]=String.valueOf(user.getUpdateTime());
            list.add(arrs);
        }
        //表头复制
        String[] head={"序号","用户名","密码","电话","创建时间","更新时间"};
        ExcelData excelData = new ExcelData();
        //头名称（字段）
        excelData.setHead(head);
        //表内数据
        excelData.setData(list);
        //导出excel的名称
        excelData.setFileName(fileName);

        //实现导出
        try {
            ExcelUtils.exportExcel(response,excelData);
            log.info("导出数据结束");
            return true;
        }catch (Exception e){
            log.info("导出数据失败");
            return false;
        }
    }


    /**
     * 方法名：
     * 功能：导入
     */
    @Override
    public Boolean importExcel(String fileName) {
        log.info("开始导入数据");
        try {
            List<Object[]> list = ExcelUtils.importExcel(fileName);

            for (int i = 0; i <list.size() ; i++) {
                User user = new User();
                user.setId(Integer.valueOf(list.get(i)[0].toString()));
                user.setUsername((String.valueOf( list.get(i)[1])));
                user.setPassword((String.valueOf( list.get(i)[2])));
                userMapper.addUser(user);
            }
            log.info("数据导入结束");
            return true;

        }catch (Exception e){
            log.info("导出数据失败");
            e.printStackTrace();
        }
        return false;
    }
}
